import {Injectable} from '@angular/core';
import {Params, PRIMARY_OUTLET, Router, UrlTree} from '@angular/router';
import {ApplocalforageService} from './applocalforage.service';
import {Demejimmer_constants} from '../const/demejimmer_constants';
import {TokenM} from '../modules/LoginMs';
import {DateTime} from 'luxon';
import {DemejimmerApiservice} from '../api/demejimmer-apiservice.service';

@Injectable({
  providedIn: 'root'
})
export class AppAuthService {

  constructor(private router: Router,
              private applocalforageService: ApplocalforageService,
              private loginApiservice: DemejimmerApiservice,
  ) {
    //1判断登录状态
    this.isLoggedIn();
  }


  /**
   * 只判断是否登录 登录后的数据在  true登录,false非登录
   */
  async isLoggedIn(): Promise<false | TokenM[]> {
    // 这里应该有检查用户登录状态的逻辑
    const tokenArr = await this.getLoginInfo();
    console.log('isLoggedIn >>getItem_token>>>', tokenArr);
    if (null === tokenArr) {
      //不存在
      return false;
    }

    //2判断 L是否有效 过期时间
    const verifyTokenL = this.verifyToken(tokenArr?.find(toke => toke.name === Demejimmer_constants.TokenL));
    if (!verifyTokenL) {
      return false;
    }

    //3判断 S的结构正常
    const tokenS = tokenArr?.find(toke => toke.name === Demejimmer_constants.TokenS);
    if (!tokenS) {
      return false;
    }

    return tokenArr;
  }

  getRedirectToLoginUrlTree(returnUrl: string): UrlTree {
    // 重定向到登录页面，并带上重定向的查询参数
    const queryParams = returnUrl ? {returnUrl} : {};
    return this.router.createUrlTree(['/' + Demejimmer_constants.LoginPath], {queryParams});
  }

  async gotoLogin() {
    //获取当前所在路由
    let currentUrlurlTree = this.getCurrentUrl();

    //获取urlTree中的urlpathappAuthService
    const currentUrlurlTreePath = currentUrlurlTree.root.children[PRIMARY_OUTLET]?.segments.map(segment => segment.path).join('/');
    console.log('refreshTokenTask currentUrlurlTree path>>>>>', currentUrlurlTreePath);
    //获取urlTree中的queryParams
    console.log('refreshTokenTask currentUrlurlTree queryParams>>>>', currentUrlurlTree?.queryParams);

    let queryParams: Params = {};
    //判断url是否 login   是queryParams保留  否全url保留
    if (currentUrlurlTreePath.startsWith(Demejimmer_constants.LoginPath)) {
      console.log("是login的url")
      queryParams = {...currentUrlurlTree?.queryParams}
    } else {
      console.log("非login的url")
      const redirectToLoginUrlTree = this.getRedirectToLoginUrlTree(currentUrlurlTree.toString());
      queryParams = redirectToLoginUrlTree?.queryParams;
    }

    this.router.navigate(['/' + Demejimmer_constants.LoginPath], {queryParams});
  }

  getCurrentUrl(): UrlTree {
    console.log('getCurrentUrl  url', this.router.url);
    return this.router.parseUrl(this.router.url);
  }

  /**
   * 验证tokenM是否有效 true有效 false无效
   * @param tokenM
   */
  verifyToken(tokenM: TokenM | undefined): boolean {
    if (!tokenM) {
      //取不到过期时间  按无效的登录处理
      console.log("expirationTimeL null 无效的token", tokenM)
      return false;
    }

    //判断过期时间
    /* console.log('tokenM', tokenM);
     console.log('DateTime.now()', DateTime.now().toString());
     console.log('DateTime.fromISO(tokenM.expirationTime)', DateTime.fromFormat(tokenM.expirationTime, "yyyy-MM-dd HH:mm:ss").toString());
    */
    //差10秒过期,按过期处理,相当于冗余10秒的量
    const now = DateTime.now();
    if (now >= DateTime.fromFormat(tokenM.expirationTime, Demejimmer_constants.DataTimeFormat).plus({seconds: -10})) {
      console.log("verifyToken>>>失败 ", now.toString(), tokenM)
      return false
    }
    return true;
  }

  async saveLogin(data: TokenM[]) {
    console.log("saveLogin>>>", data)
    await this.applocalforageService.setItem(Demejimmer_constants.AuthToken, data);
  }

  async getLoginInfo(): Promise<TokenM[] | null> {
    return await this.applocalforageService.getItem<TokenM[]>(Demejimmer_constants.AuthToken);
  }

  async refreshToken(tokenArr: TokenM[]) {
    const tokenMS = tokenArr?.find(toke => toke.name === Demejimmer_constants.TokenS);
    if (!tokenMS) {
      throw new Error('tokenS不存在,无法刷新TokenS');
    }

    const tokenML = tokenArr?.find(toke => toke.name === Demejimmer_constants.TokenL);
    if (!tokenML) {
      throw new Error('tokenL不存在,无法刷新TokenS');
    }

    if (this.verifyToken(tokenMS)) {
      //tokenMS正常无需刷新
      console.log('tokenMS 正常');
    } else {
      //需要刷新tokens
      console.log("tokenMS过期", tokenMS);
      //这里基于local 实现统一 防止多tab 导致多次刷新
      //获取锁,获取到锁调接口,没获取到锁直接返回
      const lock = await this.applocalforageService.getLock(Demejimmer_constants.RefreshTokenLock.lockKey, Demejimmer_constants.RefreshTokenLock.lockTimeOut);
      if (lock) {
        this.loginApiservice.refreshToken(tokenML)
          .subscribe({
            error: (error) => {
              // 处理api调用错误
              console.error('refreshToken failed', error);
            },
            next: (response) => {
              console.log("refreshToken>response", response);
              this.saveLogin(response.data);
              //刷新token成功
              this.applocalforageService.delLock(Demejimmer_constants.RefreshTokenLock.lockKey, lock);
            }
          });
      }
    }
  }
}


